using System.Html;
using System.Runtime.CompilerServices;
using Awaiter;
using jQueryApi;
using Nsb.Classes;

namespace Yoshi.Clusters
{
    [IgnoreNamespace]
    public class EmailCluster : EmailBase
    {
        private const int MonitorInterval = 5000;
        private static int _timer;
        public static bool MonitorInbox = true;

        public EmailCluster(EmailCluster cluster) : base(cluster)
        {
            EmailCluster = this;
        }

        public override EmailBase Build(bool active)
        {
            // Take over the Element
            Element = jQuery.FromHtml("<div class='EmailBubble Composite'/>")
                ;

            Initialize(active);

            EmailInbox = (EmailInbox)new EmailInbox(this).FromHtml("<div class='Inbox'/>");
            EmailProfile = (EmailProfile)new EmailProfile(this).FromHtml("<div class='Profile'/>");
            EmailBubbles = (EmailBubbles)new EmailBubbles(this).FromHtml("<div class='Bubbles'/>");

            HookupAll(this);

            EmailInbox.Build(true).Element.AppendTo(Element);
            EmailProfile.Build(true).Element.AppendTo(Element);
            EmailBubbles.Build(true).Element.AppendTo(Element);

            new Await()
                .AddAw(EmailInbox.RefreshAw)
                .AddDx(
                    delegate
                    {
                        Window.ClearInterval(_timer);
                        _timer = Window.SetInterval(MonitorLoop, MonitorInterval);
                        MonitorLoop();
                    }
                )
                .Commit();

            return this;
        }

        public override EmailBase Fill(object item)
        {
            throw Exceptions.NotImplementedException();
        }

        public void Destroy()
        {
            Window.ClearInterval(_timer);
            _timer = 0;
        }


        private void MonitorLoop()
        {
            Inform.Trace("{0}.MonitorLoop", GetType().Name);
            if (MonitorInbox)
            {
                EmailInbox.RefreshAw(Await.AsyncAw);
            }
        }
    }
}